from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.permissions import IsAuthenticated
from datetime import date, timedelta

from goods.models import GoodsVisitCount
from meiduo_admin.serializers.statistical import GoodsSerializer
from users.models import User


class TotalView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        count = User.objects.filter(is_staff=False).count()
        today = date.today()
        return Response({
            'count': count,
            'date': today
        })


class IncrementView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        today = date.today()

        count = User.objects.filter(is_staff=False, date_joined__gte=today).count()
        return Response({
            "count": count,
            "date": today
        })


class ActiveView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        today = date.today()

        count = User.objects.filter(is_staff=False, last_login__gte=today).count()
        return Response({
            "count": count,
            "date": today
        })


class OrdersView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        today = date.today()

        count = User.objects.filter(is_staff=False, orders__create_time__gte=today).count()
        return Response({
            "count": count,
            "date": today
        })


class MonthView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        today = date.today()

        month_today = today - timedelta(day=30)

        month_list = []

        for i in range(30):
            begin_date = month_today + timedelta(days=i)

            end_date = month_today + timedelta(days=i + 1)

            count = User.objects.filter(is_staff=False, date_joined__gte=begin_date, date_joined__lt=end_date).count()
            month_list.append({
                "count": count,
                "date": today
            })

        return Response(month_list)


class GoodsView(APIView):
    permission_classes = [IsAuthenticated]

    def get(self, request):
        today = date.today()
        data = GoodsVisitCount.objects.filter(date=today)

        ser = GoodsSerializer(data, many=True)

        return Response(ser.data)
